package com.wenda.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wenda.bean.ResultBean;
import com.wenda.entity.User;
import com.wenda.service.UserService;

@Controller
public class UserController {
	@Autowired
	UserService userService;
	//异步校验密码
	@ResponseBody
	@RequestMapping(value="/user/check",method=RequestMethod.POST)
	public ResultBean checkData(String password,HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		if(!user.getPassword().equals(password.trim())) {
			return ResultBean.build(500, "原密码错误");
		} else {
			return ResultBean.build(200, "密码正确");
		}
	}
	
	@RequestMapping(value="user/{id}",method=RequestMethod.POST)
	public String updatPwd(User user,String repeatPwd,HttpServletRequest request) {
		if(!user.getPassword().equals(repeatPwd.trim())) {
			request.setAttribute("msg", "前后密码不一致");
			return "user/modify";
		} else {
			if(userService.updateUser(user)){
				request.setAttribute("msg", "密码修改成功，下次登录时生效");
				return "user/modify";
			} else{
				request.setAttribute("msg", "服务器异常");
				return "user/modify";
			}
		}
	}
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request) {
		//移出session，转发至登录页面
		request.getSession().removeAttribute("user");
		return "redirect:/";
	}
	
	@RequestMapping(value="/email", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,String> getVerifyCode(String email) {
		String result = "";
		if(email == null || email.trim().equals("")) {
			result = "请输入邮箱";
		}else {
			result = userService.sendMial(email);
		}
		System.out.println(result);
		Map<String,String> map = new HashMap<String,String>();
		map.put("result", result);
		return map;
		
	}
	
	@RequestMapping(value="/resetPwd",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,String> restPwd(User user) {
		String result= "";
		Map<String,String> map =  new HashMap<String,String>();
		if(user == null) {
			result = "请输入邮箱";
			
		} else if(user.getPassword() == null || user.getPassword().trim().equals("")) {
			result = "请输入密码";
		}else if(user.getVerifycode() == null || user.getVerifycode().trim().equals("")) {
			result = "请输入验证码";
		}else {
			result = userService.resetPwd(user);
		}
		map.put("result", result);
		return map;
	}
	
}
